<?php

class SiteController extends FrontEndController {

    public function filters() {
        return array(
            'accessControl',
            'postOnly + delete'
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     *
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array(
                'allow',
                'actions' => array(
                    'newsfeed',
                    'notify',
                    'newsfeedmore',
                    'newsfeedmore2'
                ),
                'roles' => array(
                    'member'
                )
            ),
            array(
                'allow',
                'actions' => array(
                    'index',
                    'new',
                    'loadmore',
                    'error',
                    'contact'
                ),
                'users' => array(
                    '*'
                )
            ),
            array(
                'deny',
                'users' => array(
                    '*'
                )
            )
        );
    }

    /**
     * Declares class-based actions.
     */
    public function actions() {
        return array(
            'captcha' => array(
                'class' => 'CCaptchaAction',
                'backColor' => 0xFFFFFF
            ),
            'page' => array(
                'class' => 'CViewAction'
            )
        );
    }

    /**
     * This is the default 'index' action that is invoked
     * when an action is not explicitly requested by users.
     */
    public function actionIndex() {
        $sql = "Select u.* From tbl_user u left join tbl_image img on u.id = img.user_created  Where u.status=:status GROUP BY u.id Order BY SUM(img.like_cnt*5 + img.view_cnt) DESC LIMIT 0,4";
        $topuser = User::model()->findAllBySql($sql, array(':status' => User::ACCOUNT_ACTIVE));
        $sql = "Select c.* From tbl_collection c Where c.status=:status Order BY c.like_cnt DESC LIMIT 0,3";
        $topcollection = Collection::model()->findAllBySql($sql, array(':status' => Collection::COLLECTION_ACTIVE));
//        $model = Image::model()->findAllBySql("SELECT *,view_cnt+(like_cnt*5)as 'hot' FROM tbl_image i join tbl_image_like ik on ik.image_id = i.id join tbl_image_view iv on iv.image_id = i.id  where status=:status ORDER BY hot DESC LIMIT 0,12", array(':status' => Image::IMAGE_ACTIVE));
        $model = Image::model()->findAllBySql("SELECT i.*,((select count(image_id) * 5 from tbl_image_like where image_id = i.id and like_at >DATE_SUB(NOW(), INTERVAL 1 DAY)) + (select count(image_id)  from tbl_image_view where image_id = i.id and view_at >DATE_SUB(NOW(), INTERVAL 1 DAY)) ) as 'hot' FROM tbl_image i where status=:status ORDER BY hot DESC LIMIT 0,12", array(':status' => Image::IMAGE_ACTIVE));
        $this->render('index', array(
            'model' => $model,
            'topuser' => $topuser,
            'topcollection' => $topcollection,
        ));
    }

    public function actionNew() {
        $criteria = new CDbCriteria();
        $criteria->compare('status', Image::IMAGE_ACTIVE);
        $criteria->order = 'created_at DESC';
        $criteria->limit = 16;
        $model = Image::model()->findAll($criteria);
        $this->render('new', array(
            'model' => $model,
        ));
    }

    public function actionLoadMore($id) {
        $models = Image::model()->findAllBySql("SELECT *,view_cnt+(like_cnt*5)as 'hot' FROM tbl_image where status=:status and view_cnt+(like_cnt*5)<:hot ORDER BY hot DESC LIMIT 0,3", array(':status' => Image::IMAGE_ACTIVE, ':hot' => $id));
        $data = array();

        foreach ($models as $model) {
            $temp = $model->attributes;
            $temp['username'] = $model->userCreated->username;
            $temp['comment_cnt'] = sizeof(Comment::model()->findAll('image_id=:id', array(':id' => $model->id)));
            $checkFollow = UserFollow::model()->find("followed = :followed and follower =:follower", array(
                ':followed' => $model->user_created,
                'follower' => Yii::app()->user->id
            ));
            $temp['isFollowed'] = $checkFollow != NULL;
            $temp['avatar'] = $model->userCreated->avatar;
            $temp['fullname'] = $model->userCreated->fullname;
            $temp['time'] = Format::timeAgo($model->created_at, 'Y-m-d H:i:s');
            $temp['view_url'] = Yii::app()->createUrl('image/view', array('id' => $model->id));
            $temp['user_url'] = Yii::app()->createUrl('user/view', array('username' => $model->userCreated->username));
            $temp['rate'] = $model->like_cnt * 5 + $model->view_cnt;
            $data[] = $temp;
        }

        unset($models);
        unset($model);
        unset($temp);
        header("HTTP/1.0 200");
        print json_encode($data);
    }

    /**
     * This is the action to handle external exceptions.
     */
    public function actionError() {
        if ($error = Yii::app()->errorHandler->error) {
            if (Yii::app()->request->isAjaxRequest)
                echo $error ['message'];
            else
                $this->render('error', $error);
        }
    }

    /**
     * Displays the contact page
     */
    public function actionContact() {
        $modelodel = new ContactForm ();
        if (isset($_POST ['ContactForm'])) {
            $modelodel->attributes = $_POST ['ContactForm'];
            if ($modelodel->validate()) {
                $name = '=?UTF-8?B?' . base64_encode($modelodel->name) . '?=';
                $subject = '=?UTF-8?B?' . base64_encode($modelodel->subject) . '?=';
                $headers = "From: $name <{$modelodel->email}>\r\n" . "Reply-To: {$modelodel->email}\r\n" . "MIME-Version: 1.0\r\n" . "Content-type: text/plain; charset=UTF-8";

                mail(Yii::app()->params ['adminEmail'], $subject, $modelodel->body, $headers);
                Yii::app()->user->setFlash('contact', 'Thank you for contacting us. We will respond to you as soon as possible.');
                $this->refresh();
            }
        }
        $this->render('contact', array(
            'model' => $modelodel
        ));
    }

    public function actionNotify() {
        $user = User::model()->findByPk(Yii::app()->user->id);
        $lstFollowedID = array();
        $modelodel = new UserActive ();
        $listImageFollow = ImageUserFollow::model()->findAll("user_id=:id", array(
            ':id' => Yii::app()->user->id
        ));
        if ((!is_null($listImageFollow)) && sizeof($listImageFollow > 0)) {

            foreach ($listImageFollow as $followed) {
                $lstFollowedID [] = $followed->image_id;
            }
            $lstFollowed = implode(",", $lstFollowedID);
//            $sql = 'SELECT t.* FROM tbl_user_active t join tbl_image img on t.image_id = img.id where t.image_id in (' . $lstFollowed . ') and t.user_id <> :id and ((img.user_created = :id or t.active_type = :active_type )) ORDER BY active_at DESC LIMIT 0 , 10';
//             $sql = 'SELECT t.* FROM tbl_user_active t join tbl_image img on t.image_id = img.id join tbl_image_user_follow img_fl on t.user_id = img_fl.user_id join tbl_user u on u.id = t.user_id where t.active_at >img_fl.follow_at and img.status = :img_status and u.status = :user_status t.image_id in (' . $lstFollowed . ') and t.user_id <> :id and ((img.user_created = :id or t.active_type = :active_type )) ORDER BY active_at DESC LIMIT 0 , 10';
            $sql = 'SELECT t.* FROM tbl_user_active t join tbl_image img on t.image_id = img.id join tbl_image_user_follow img_fl on t.image_id = img_fl.image_id join tbl_user u on u.id = t.user_id where img_fl.user_id =:id and t.active_at >img_fl.follow_at and img.status = :img_status and u.status = :user_status and t.image_id in (' . $lstFollowed . ') and t.user_id <> :id and ((img.user_created = :id or t.active_type = :active_type )) ORDER BY active_at DESC LIMIT 0 , 10';
            $modelodel = UserActive::model()->findAllBySql($sql, array(
                ':id' => Yii::app()->user->id,
                ':active_type' => UserActive::COMMENT_IMG
                     ,':user_status'=>User::ACCOUNT_ACTIVE
                     ,':img_status'=>Image::IMAGE_ACTIVE
            ));
            var_dump($lstFollowed);
            var_dump($modelodel);
            exit();
            unset($sql);
            unset($user);
            unset($lstFollowed);
            $this->render('notify', array(
                'model' => $modelodel
            ));
            
        } else {
            $this->render('notify', array(
                'model' => null
            ));
        }
    }

    public function actionNewsFeed() {
        if (!Yii::app()->user->isGuest) {
            $user = User::model()->findByPk(Yii::app()->user->id);
            $lstFollowedID = array();
            if (sizeof($user->userFollow) > 0) {
                foreach ($user->userFollow as $followed) {
                    $lstFollowedID [] = $followed->followed;
                }
                $lstFollowed = implode(",", $lstFollowedID);
// 			$sql = 'SELECT * FROM tbl_user_active t join tbl_user u on t.user_id = u.id join tbl_image img on img.id = t.image_id  WHERE img.status = :img_status and u.status = :user_status and t.user_id in (' . $lstFollowed . ') ORDER BY active_at DESC LIMIT 0 , 10';
                $sql = 'SELECT * FROM tbl_user_active WHERE user_id in (' . $lstFollowed . ') ORDER BY active_at DESC LIMIT 0 , 10';
                $model = UserActive::model()->findAllBySql($sql, array(
// 					':user_status' => User::ACCOUNT_ACTIVE 
// 					,':img_status'=>Image::IMAGE_ACTIVE
                ));
                unset($sql);
                unset($user);
                unset($lstFollowed);
                $this->render('newsfeed', array(
                    'model' => $model
                ));
            } else {
                $this->render('newsfeed', array(
                    'model' => null
                ));
            }
        }
    }
    public function actionNewsFeedmore() {
        if (!Yii::app()->user->isGuest) {
            $user = User::model()->findByPk(Yii::app()->user->id);
            $lstFollowedID = array();
            $modelodel = new UserActive ();
            if (sizeof($user->userFollow) > 0) {

                foreach ($user->userFollow as $followed) {
                    $lstFollowedID [] = $followed->followed;
                }
                $lstFollowed = implode(",", $lstFollowedID);
                // 			$sql = 'SELECT * FROM tbl_user_active t join tbl_user u on t.user_id = u.id join tbl_image img on img.id = t.image_id  WHERE t.id > :id and img.status = :img_status and u.status = :user_status and t.user_id in (' . $lstFollowed . ') ORDER BY active_at DESC LIMIT 0 , 10';
                $sql = 'SELECT * FROM tbl_user_active WHERE id > :id and user_id in (' . $lstFollowed . ') ORDER BY active_at DESC LIMIT 0 , 10';
                do {
                    sleep(3);
                    $modelodel = UserActive::model()->findAllBySql($sql, array(':id' => $_GET['id']));
//                    $modelodel = UserActive::model()->findAllBySql($sql, array(':id' => $_GET['id'],':user_status' => User::ACCOUNT_ACTIVE, ':img_status'=>Image::IMAGE_ACTIVE));
                } while (sizeof($modelodel) == 0);
                $data = array();

                foreach ($modelodel as $model) {
                    $data[] = array(
                        'id' => $model->id,
                        'user_fn' => $model->user->fullname,
                        'active_type' => $model->active_type,
                        'img_id' => $model->image->id,
                        'img_url' => $model->image->img_url,
                        'img_title' => $model->image->title,
                        'active_at' => $model->active_at,
                    );
                }
                unset($sql);
                unset($user);
                unset($lstFollowed);
                header("HTTP/1.0 200");
                print json_encode($data);
            }
        }
    }

}